import openai
from flask import Flask, request, jsonify, make_response

# 设置你的OpenAI API密钥
openai.api_key = "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"

# 创建Flask应用
app = Flask(__name__)

# 读取txt文件的内容
def read_txt_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

# 将文件内容与GPT交互
def interact_with_gpt(file_content, origin_text, user_input):
    messages = [
        {"role": "system", "content": "你是一位非常聪明的博客助手，我会提前给你一些词语以及一个文本样本，然后我会给你输入一个原始的句子，尽可能用上这些词和风格，改写句子，不改变原文意思。"},
        {"role": "user", "content": f"请参考以下词语，并根据这些内容回答：\n{file_content}"},
        {"role": "user", "content": f"以下是参考的写作风格样本：\n{origin_text}"},
    ]
    messages.append({"role": "user", "content": user_input})
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=messages
        )
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"Error generating chat response: {e}"

# 添加跨域支持
@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    return response

# GET接口
@app.route('/status', methods=['GET'])
def status():
    return jsonify({"status": "OK", "message": "服务正常运行中"})

# POST接口
@app.route('/process_input', methods=['POST'])
def process_input():
    try:
        file_path = "prompt-100.txt"
        prompt_content = read_txt_file(file_path)
        origin_file_path = "origin-text.txt"
        origin_text = read_txt_file(origin_file_path)
        user_input = request.json.get("user_input")
        if not user_input:
            return jsonify({"error": "未提供用户输入"}), 400
        result = interact_with_gpt(prompt_content, origin_text, user_input)
        return jsonify({"response": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 主程序启动Flask服务
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=1414, debug=True)
